# apps/address/middleware.py
from django.core.exceptions import PermissionDenied

class AddressOwnershipMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 延迟导入模型
        from .models import Address
        self.Address = Address  # 缓存供后续使用
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        if 'pk' in view_kwargs and request.path.startswith('/api/address/'):
            Address = self.Address  # 使用缓存的模型引用
            address = Address.objects.get(pk=view_kwargs['pk'])
            if address.user_id != request.user.id:
                raise PermissionDenied("无权操作该地址")